import api from '@/store/api';
// import i18n from '@/i18n';
import { ReturnGetters, ActionContext } from '@/types/store';

const state = {
  information: {},
  list: [] as any[],
  chassisId: [] as string[],
};
type State = typeof state;

const getters = {
  list: (state: State) => state.list,
  information: (state: State) => state.information,
  chassisId: (state: State) => state.chassisId,
};
type Getters = ReturnGetters<typeof getters>;

const mutations = {
  setInformation(state: State, information: any) {
    state.information = information;
  },
  setList(state: State, list: any[]) {
    state.list = list;
  },
  setChassisId: (state: State, chassisId: string[]) => {
    state.chassisId = chassisId;
  },
};
type Multations = keyof typeof mutations;

const actionsNames = [
  'getChassisId',
  'updateBiosHash',
  'initAccount',
  'updateStrategy',
  'deleteStrategy',
  'getTpcmInformation',
  'getTpcmList',
] as const;
type ActionNames = typeof actionsNames[number];

const actions = {
  async getChassisId({
    commit,
  }: ActionContext<ActionNames, Multations, State, Getters>) {
    let chassisId: string[] = [];
    await api.get('/redfish/v1/Chassis/').then(({ data: { Members } }) => {
      for (let member of Members) {
        let chassisUrl = Object.values(member)[0] as string;
        chassisId.push(chassisUrl.split('/')[chassisUrl.split('/').length - 1]);
      }
    });
    commit('setChassisId', chassisId);
    return chassisId;
  },
  async updateBiosHash(
    { dispatch }: ActionContext<ActionNames, Multations, State, Getters>,
    { username, password }: { username: string; password: string }
  ) {
    let ChassisId = await dispatch('getChassisId')[0];
    return await api
      .post(
        `/redfish/v1/Chassis/${ChassisId}/TrustedComponents/phyTee/OemActions/TrustedComponents.PcrExtend`,
        { UserName: username, Password: password }
      )
      .then((response) => console.dir(response));
  },
  async initAccount(
    { dispatch }: ActionContext<ActionNames, Multations, State, Getters>,
    { username, password }: { username: string; password: string }
  ) {
    let ChassisId = await dispatch('getChassisId')[0];
    return await api
      .post(
        `/redfish/v1/Chassis/${ChassisId}/TrustedComponents/phyTee/OemActions/TrustedComponents.PwdInit`,
        { UserName: username, Password: password }
      )
      .then((response) => console.log('PwdInit response' + response));
  },
  async updateStrategy(
    { dispatch }: ActionContext<ActionNames, Multations, State, Getters>,
    {
      url,
      username,
      password,
      measurementReference,
      id,
      name,
      measurementHashAlgorithm,
      controlModel,
    }: {
      url: string;
      username: string;
      password: string;
      measurementReference: string;
      id: string;
      name: string;
      measurementHashAlgorithm: string;
      controlModel: string;
    }
  ) {
    return await api
      .patch(url, {
        UserName: username,
        Password: password,
        Id: id,
        Name: name,
        MeasurementReference: measurementReference,
        MeasurementHashAlgorithm: measurementHashAlgorithm,
        ControlModel: controlModel,
      })
      .then((response) => console.dir(response));
  },
  async deleteStrategy(
    { dispatch }: ActionContext<ActionNames, Multations, State, Getters>,
    {
      url,
      username,
      password,
    }: { url: string; username: string; password: string }
  ) {
    return await api
      .delete(url, {
        params: { UserName: username, Password: password },
      })
      .then((response) => console.dir(response));
  },
  async getTpcmInformation({
    commit,
    dispatch,
  }: ActionContext<ActionNames, Multations, State, Getters>) {
    let ChassisId = await dispatch('getChassisId')[0];
    return await api
      .get(`/redfish/v1/Chassis/${ChassisId}/TrustedComponents/phyTee`)
      .then((response: any) => {
        const information = {
          firmwareId: response.data.Id,
          firmwareVersion: response.data.FirmwareVersion,
          manufacturer: response.data.Manufacturer,
          trustedComponentType: response.data.TrustedComponentType,
          initStatus: response.data.Oem.InitStatus,
        };
        commit('setInformation', information);
      })
      .catch((error) => {
        console.log(error);
      });
  },
  async getTpcmList({
    commit,
  }: ActionContext<ActionNames, Multations, State, Getters>) {
    return await api
      .get(`/redfish/v1/ComponentIntegrity/`)
      .then((response: any) => {
        const list = response.data.Members.map((data: any) => {
          return {
            Id: data.Id,
            Name: data.Name,
            MeasurementHashAlgorithm:
              data.Oem.MeasurementSet.Measurements.MeasurementHashAlgorithm,
            Measurement: data.Oem.MeasurementSet.Measurements.Measurement,
            MeasurementReference: data.Oem.MeasurementSet.MeasurementReference,
            ControlModel: data.Oem.MeasurementSet.ControlModel,
            Consistence: data.Oem.MeasurementSet.Consistence,
            PCR: data.Oem.MeasurementSet.Measurements.PCR,
            url: data['@odata.id'],
          };
        });
        commit('setList', list);
      })
      .catch((error) => {
        console.log(error);
      });
  },
};

const TrustedComputingStore = {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
};

export default TrustedComputingStore;
